import React, { Component } from 'react';
import * as RecordsAPI from '../utils/RecordsAPI';
import Record from './Record';
import RecordForm from './RecordForm';
import AmountBox from './AmountBox';

/*
  Jquery 请求
  no.1 
    import { getJSON }from 'jquery';

  no.2 
    componentDidMount(){
      getJSON("https://5b8f60c8eb676700148a4cea.mockapi.io/api/v1/records").then(
        res => this.setState({
          records : res,
          isLoaded: true
        }),
        error => this.setState({
          isLoaded : true,
          error,
        })
      )
    }
*/

class Records extends Component {
  constructor(){
    super();
    this.state = {
      error   : null,
      isLoaded: false,
      records : []
    }
  }
  
  componentDidMount(){
    RecordsAPI.getAll().then(
      res => this.setState({
        records : res.data,
        isLoaded: true
      })
    ).catch(
      error => this.setState({
        isLoaded : true,
        error,
      })
    )
  }

  addRecord(record) {
    this.setState({
      error   : null,
      isLoaded: true,
      /*es6 语法 把...this.state.records 里面的对象和传过来record对象合并在一起给records*/
      records : [
        ...this.state.records,
        record
      ]
    })
  }
  
  updateRecord(record,data){
    //替换数组元素
    const recordIndex = this.state.records.indexOf(record);
    const newRecords = this.state.records.map((item,index) => {
      if(index !== recordIndex) {
        return item;
      }
      /*data的值去替换item的值*/
      return {
        ...item,
        ...data
      };
    });
    this.setState({
      records : newRecords
    })
  }

  deleteRecord(record) {
    const recordIndex = this.state.records.indexOf(record);
    const newRecords = this.state.records.filter((item,index) => index !== recordIndex);
    this.setState({
      records : newRecords
    })
  }

  credits() {
    let credits = this.state.records.filter((record) => {
      return record.amount >= 0;
    })
    return credits.reduce((prev,curr) => {
      return prev + Number.parseInt(curr.amount,0)
    },0)
  }

  debits() {
    let credits = this.state.records.filter((record) => {
      return record.amount < 0;
    })
    return credits.reduce((prev,curr) => {
      return prev + Number.parseInt(curr.amount,0)
    },0)
  }

  balance() {
    return this.credits() + this.debits();
  }

  render() {
     const {error,isLoaded,records} = this.state;
     let recordsComponent;

     if(error){
        recordsComponent = <div><h3>Error:</h3>{error.message}</div>
     }else if(!isLoaded){
        recordsComponent = <div><h6>Loading......</h6></div>  
     }else {
        recordsComponent = (
          <table className="table table-bordered">
            <thead>
              <tr>
                <th>Date</th>
                <th>Title</th>
                <th>Amount</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              {records.map((record,index) => (
                <Record 
                  key={record.id} 
                  record={record} 
                  handleEditRecord={this.updateRecord.bind(this)} 
                  handleDeleteRecord={this.deleteRecord.bind(this)}
                />
              ))}
            </tbody>
          </table>
        );
     }

    return (
      <div>
        <h2>记账本</h2>
        <div className="row mb-3">
          <AmountBox text="Credit" type="success" amount={this.credits()}/>
          <AmountBox text="Debit" type="danger" amount={this.debits()}/>
          <AmountBox text="Balance" type="info" amount={this.balance()}/>
        </div>
        <RecordForm handleNewRecord={this.addRecord.bind(this)} />
        {recordsComponent}
      </div>
    ); 
  }
}

export default Records;
